package com.sita.tboard.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.colintmiller.simplenosql.NoSQL;
import com.colintmiller.simplenosql.NoSQLEntity;
import com.colintmiller.simplenosql.RetrievalCallback;
import com.nostra13.universalimageloader.utils.L;
import com.sita.bike.R;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Account;
import com.sita.bike.rest.model.AccountListResponse;
import com.sita.bike.rest.model.Location;
import com.sita.bike.rest.model.SearchNearlyPersonRequest;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.LogUtils;
import com.sita.bike.utils.PersistUtils;
import com.sita.friend.ui.activity.FriendDetailActivity;
import com.sita.tboard.global.LocalConstants;
import com.sita.tboard.ui.view.CircleImageView;
import com.sita.tboard.ui.view.RefreshListView;
import com.sita.tboard.util.DistanceUtil;
import com.sita.tboard.util.NumberUtils;
import com.squareup.picasso.Picasso;

import java.util.LinkedList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

//import com.nostra13.universalimageloader.core.ImageLoader;

public class DiscoveryPeopleFragment extends Fragment implements RefreshListView.OnRefreshListener {
    private AccountAdapter adapter;
    private int mPageNumber = 0;
    private boolean mIsRefresh = true;
    private boolean mIsRequesting = false;

    private int mPageSize = 15;
    private boolean mIsFirstRun = true;
    @Bind(R.id.refreshlistview)
    RefreshListView mListView;

    private Parcelable mListViewtSate;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_discovery_people, null);
        ButterKnife.bind(this, view);
        mListView.setOnRefreshListener(this);
        return view;
    }

    class ListItemView {                //自定义控件集合
        CircleImageView user_profile;
        ImageView user_sex;
        TextView user_name;
        TextView user_distance;
    }

    private class AccountAdapter extends BaseAdapter {
        private Context context;                        //运行上下文
        private LinkedList<Account> accounts = new LinkedList<Account>();    //商品信息集合
        private LayoutInflater listContainer;           //视图容器

        public AccountAdapter(Context context) {
            this.context = context;
            listContainer = LayoutInflater.from(context);
        }

        void setListItems(List<Account> mListItems) {
            accounts.clear();
            accounts.addAll(mListItems);
            notifyDataSetChanged();
        }

        public void addItem(Account account) {
            LogUtils.i("people", "account : "+ account.mMobile + "," + account.mNickName);
            if (!accounts.contains(account)) {
                accounts.add(account);
                notifyDataSetChanged();
            }
        }

        public void addTop(Account account) {
            LogUtils.i("people", "account : "+ account.mMobile + "," + account.mNickName);
            accounts.addFirst(account);
            notifyDataSetChanged();
        }

        public void appendBottom(Account account) {
            accounts.addLast(account);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return accounts.size();
        }

        @Override
        public Account getItem(int position) {
            return accounts.get(position);
        }

        public LinkedList<Account> getItems() {
            return accounts;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Log.d("DiscoveryPeopleFragment", "getView @" + position);
            //自定义视图
            ListItemView listItemView = null;
            if (convertView == null) {
                Log.d("DiscoveryPeopleFragment", "getView create new ");
                listItemView = new ListItemView();
                //获取list_item布局文件的视图
                convertView = listContainer.inflate(R.layout.discovery_people_list_item, null);
                //获取控件对象
                listItemView.user_profile = (CircleImageView) convertView.findViewById(R.id.user_profile);
                listItemView.user_name = (TextView) convertView.findViewById(R.id.user_name);
                listItemView.user_sex = (ImageView) convertView.findViewById(R.id.user_sex);
                listItemView.user_distance = (TextView) convertView.findViewById(R.id.user_distance);

                //设置控件集到convertView
                convertView.setTag(listItemView);
            } else {
                listItemView = (ListItemView) convertView.getTag();
            }

            final Account account = getItem(position);

            listItemView.user_name.setText(AccountUtils.getUserDisplayName(account));
            listItemView.user_sex.setImageBitmap(null);
            listItemView.user_profile.setImageBitmap(null);
            String avatar = account.mAvatar;

            Picasso.with(GlobalContext.getGlobalContext()).load(avatar)
                    .fit().centerInside().into(listItemView.user_profile);

            listItemView.user_profile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    browseAccount(account);
                }
            });
            listItemView.user_name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    browseAccount(account);
                }
            });

//            changeSex(account.mGender, listItemView);

            String distance = null;
            if (!(TextUtils.isEmpty(account.mLat) && TextUtils.isEmpty(account.mLng))) {
                AMapLocation currLocation = GlobalContext.getLocationClient().getLastKnownLocation();
                double myLng = currLocation.getLongitude();
                double myLat = currLocation.getLatitude();

                double dist = DistanceUtil.getDistance(Double.valueOf(account.mLng),
                        Double.valueOf(account.mLat), myLng, myLat) / 1000;
                distance = NumberUtils.formatNumber(dist) + " km";
            }

            //listItemView.user_distance.setText(distance);

            return convertView;
        }

        private void browseAccount(Account account) {
            Intent intent = new Intent(getActivity().getBaseContext(), FriendDetailActivity.class);
            intent.putExtra(LocalConstants.BUNDLE_ACCOUNT_ID, account.mAccountId);
            startActivity(intent);
        }

    }

    @Override
    public void onDownPullRefresh() {
        if (mIsRequesting) {
            return;
        }
        mIsRefresh = true;
        getAllAccount();

    }

    @Override
    public void onLoadingMore() {
        if (mIsRequesting) {
            return;
        }
        mIsRefresh = false;
        getAllAccount();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (adapter == null) {
            adapter = new AccountAdapter(getActivity().getApplicationContext());
            mListView.setAdapter(adapter);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mListViewtSate != null) {
            L.d("trying to restore listview state..");
            mListView.onRestoreInstanceState(mListViewtSate);
        } else {
            loadData();
        }
        if (adapter.getItems().isEmpty()) {
            onDownPullRefresh();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mListViewtSate = mListView.onSaveInstanceState();
    }

    public void getAllAccount() {
        mIsRequesting = true;

        mPageNumber = (mIsRefresh) ? 0 : mPageNumber + 1;

        RestClient.getRestNormalService().listAccounts(mPageNumber, mPageSize, new Callback<AccountListResponse>() {
            @Override
            public void success(AccountListResponse listResponse, Response response) {
                if (response.getStatus() == 200) {
                    if (listResponse.mErrorCode.equals("0") && listResponse.mData != null
                            && !listResponse.mData.isEmpty()) {

//                        for (Account account : listResponse.mData) {
                        if (mIsRefresh){
                            for (int i = listResponse.mData.size(); i > 0; i--) {
                                Account account = listResponse.mData.get(i - 1);
                                adapter.addTop(account);

                                PersistUtils.saveTrendMember(account);
                            }
                        } else {
                            for (int i = 0; i < listResponse.mData.size(); i++) {
                                Account account = listResponse.mData.get(i);
                                adapter.addItem(account);
                                // TODO: 2016/3/17
                                PersistUtils.saveTrendMember(account);
//                            NoSQLEntity<Account> entity = new NoSQLEntity<Account>(Constants.ACCOUNT_BUCKET, account.mAccountId, account);
//                            NoSQL.with(GlobalContext.getGlobalContext()).using(Account.class)
//                                    .save(entity);
                            }
                        }
                    }
                }

                if (mIsRefresh) {
                    mListView.hideHeaderView();
                } else {
                    mListView.hideFooterView();
                }
                mIsRequesting = false;
            }

            @Override
            public void failure(RetrofitError error) {
                L.e(error);
                if (mIsRefresh) {
                    mListView.hideHeaderView();
                } else {
                    mListView.hideFooterView();
                }
                mPageNumber -= 1;
                mIsRequesting = false;
            }
        });

    }

    public void getNearlyPerson() {
        mIsRequesting = true;

        SearchNearlyPersonRequest nearlyPersonRequest = new SearchNearlyPersonRequest();
        nearlyPersonRequest.mAccountId = AccountUtils.getAccountID();
        AMapLocation currLoc = GlobalContext.getLocationClient().getLastKnownLocation();
        Location location = new Location();
        location.latitude = String.valueOf(currLoc.getLatitude());
        location.longitude = String.valueOf(currLoc.getLongitude());
        location.province = currLoc.getProvince();
        location.city = currLoc.getCity();
        nearlyPersonRequest.location = location;
        nearlyPersonRequest.mGeofence = 5000;
        mPageNumber = (mIsRefresh) ? 0 : mPageNumber + 1;
        nearlyPersonRequest.mPageNumber = String.valueOf(mPageNumber);
        nearlyPersonRequest.mPageSize = String.valueOf(mPageSize);

        RestClient.getRestNormalService().searchNearlyAccounts(nearlyPersonRequest, new Callback<AccountListResponse>() {
            @Override
            public void success(AccountListResponse listResponse, Response response) {
                if (response.getStatus() == 200) {
                    if (listResponse.mErrorCode.equals("0") && listResponse.mData != null
                            && !listResponse.mData.isEmpty()) {

                        for (Account account : listResponse.mData) {
                            adapter.addItem(account);
                            NoSQLEntity<Account> entity = new NoSQLEntity<Account>(Constants.ACCOUNT_BUCKET, account.mAccountId, account);
                            NoSQL.with(GlobalContext.getGlobalContext()).using(Account.class)
                                    .save(entity);
                        }
                    }
                }

                if (mIsRefresh) {
                    mListView.hideHeaderView();
                } else {
                    mListView.hideFooterView();
                }
                mIsRequesting = false;
            }

            @Override
            public void failure(RetrofitError error) {
                L.e(error);
                if (mIsRefresh) {
                    mListView.hideHeaderView();
                } else {
                    mListView.hideFooterView();
                }
                mPageNumber -= 1;
                mIsRequesting = false;
            }
        });

    }

//    public void changeSex(int i, ListItemView listItemView) {
//        if (i == 0) {
//
//        } else if (i == 1) {
//            listItemView.user_sex.setImageDrawable(getResources().getDrawable(R.drawable.male));
//        } else if (i == 2) {
//            listItemView.user_sex.setImageDrawable(getResources().getDrawable(R.drawable.female));
//        }
//    }

    private void loadData() {
        NoSQL.with(getContext().getApplicationContext()).using(Account.class)
                .bucketId(Constants.ACCOUNT_BUCKET)
                .retrieve(new RetrievalCallback<Account>() {
                    @Override
                    public void retrievedResults(List<NoSQLEntity<Account>> noSQLEntities) {
                        for (NoSQLEntity<Account> entity : noSQLEntities) {
                            Account dr = entity.getData();
                            adapter.addItem(dr);
                        }
                    }
                });
    }
}
